const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const { SerialPort } = require('serialport')

let mainWindow
let serialPort

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true
    }
  })

  // 检查是否是开发环境
  if (process.env.NODE_ENV === 'development') {
    // 在开发环境中加载 Vite 开发服务器
    mainWindow.loadURL('http://localhost:5173')
    // 打开开发者工具
    mainWindow.webContents.openDevTools()
  } else {
    // 在生产环境中加载打包后的文件
    mainWindow.loadFile('dist/index.html')
  }
  
  // 添加调试信息
  mainWindow.webContents.on('did-finish-load', () => {
    console.log('Window finished loading');
    mainWindow.webContents.executeJavaScript(`
      console.log('Window context - serialAPI exists:', typeof window.serialAPI);
    `);
  });
}

// 处理串口相关IPC消息
ipcMain.handle('serial:list-ports', async () => {
  try {
    console.log('Listing serial ports...');
    const ports = await SerialPort.list()
    console.log('Found ports:', ports);
    return ports
  } catch (error) {
    console.error('Error listing ports:', error)
    throw error
  }
})

ipcMain.handle('serial:connect', async (event, portPath, options) => {
  return new Promise((resolve, reject) => {
    try {
      console.log(`Attempting to connect to ${portPath} with options:`, options);
      
      // 如果已有连接，先断开
      if (serialPort && serialPort.isOpen) {
        console.log('Closing existing connection...');
        serialPort.close();
      }
      
      serialPort = new SerialPort({ 
        path: 'COM1',
        baudRate: options.baudRate || 115200,
        autoOpen: false // 先不自动打开
      })

      serialPort.on('open', () => {
        console.log(`Serial port ${portPath} opened successfully`)
        resolve(`Serial port ${portPath} opened`)
      })

      serialPort.on('data', (data) => {
        console.log('Received data:', data.toString())
        mainWindow.webContents.send('serial:receive-data', data.toString())
      })

      serialPort.on('error', (error) => {
        console.error('Serial port error:', error.message)
        mainWindow.webContents.send('serial:receive-error', error.message)
        reject(error)
      })
      
      serialPort.on('close', () => {
        console.log(`Serial port ${portPath} closed`)
      })

      // 手动打开串口
      serialPort.open((error) => {
        if (error) {
          console.error('Failed to open serial port:', error)
          reject(error)
        } else {
          console.log(`Serial port ${portPath} opened successfully`)
        }
      })
    } catch (error) {
      console.error('Exception in serial connect:', error)
      reject(error)
    }
  })
})

ipcMain.handle('serial:disconnect', async () => {
  return new Promise((resolve, reject) => {
    if (serialPort) {
      console.log('Closing serial port...');
      serialPort.close((error) => {
        if (error) {
          console.error('Error closing serial port:', error);
          reject(error)
        } else {
          console.log('Serial port closed successfully');
          resolve('Serial port closed')
        }
      })
    } else {
      console.log('No serial port to close');
      resolve('Serial port not open')
    }
  })
})

ipcMain.handle('serial:send-data', async (event, data) => {
  return new Promise((resolve, reject) => {
    if (serialPort && serialPort.isOpen) {
      // 支持多种数据格式发送
      let dataToSend;
      
      // 如果是字符串，直接发送
      if (typeof data === 'string') {
        dataToSend = data;
      } 
      // 如果是数组，转换为Buffer
      else if (Array.isArray(data)) {
        dataToSend = Buffer.from(data);
      } 
      // 其他情况转换为字符串
      else {
        dataToSend = String(data);
      }
      
      console.log('Sending data:', dataToSend);
      serialPort.write(dataToSend, (error) => {
        if (error) {
          console.error('Error sending data:', error);
          reject(error)
        } else {
          console.log('Data sent successfully');
          resolve('Data sent')
        }
      })
    } else {
      const errorMsg = 'Serial port not open';
      console.error(errorMsg);
      reject(new Error(errorMsg))
    }
  })
})

app.whenReady().then(() => {
  console.log('App is ready');
  createWindow()
})

// 当所有窗口都关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})
